package com.redside.dao.spring;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.exception.DataException;
import org.springframework.jdbc.core.RowMapper;

import com.redside.dao.OptionsBeanLookupDao;
import com.redside.model.list.OptionsBean;

public class OptionsBeanLookupDaoSpring  extends JdbcGenericListService implements OptionsBeanLookupDao {

    @SuppressWarnings("unchecked")
    public List<OptionsBean> findAll(String sql)  throws DataException{
        return getJdbcTemplate().query(getSQL(sql), new ListHandler());
    }
    
    @SuppressWarnings("unchecked")
    public List<OptionsBean> findAllForTag(String sql) throws DataException{
    	logger.debug("=================getting list from Dao======================");
    	try{
    		logger.debug("==>connection: "+getJdbcTemplate().getDataSource().getConnection());	
    	}catch(SQLException se){
    		se.printStackTrace();
    	}
        return getJdbcTemplate().query(getSQL(sql), new ListHandler());
    }
    
    @SuppressWarnings("unchecked")
    public List<OptionsBean> findAll(String sql, String defaultId, String defaultValue) throws DataException{
        List<OptionsBean> options = getJdbcTemplate().query(getSQL(sql), new ListHandler());
        options.add(0,new OptionsBean(defaultId,defaultValue));
        return options;
    }

    @SuppressWarnings("unchecked")
    public OptionsBean findById(String sql, Long id)  throws DataException{
        
        Object[] params = new Object[] {id};
        List<OptionsBean> options = getJdbcTemplate().query(getSQL(sql),params,
                new ListHandler());
        return options.size() > 0 ? (OptionsBean)options.get(0) : null;
    }
    
    @SuppressWarnings("unchecked")
    public OptionsBean findById(String sql, String id)  throws DataException{
        
        Object[] params = new Object[] {id};
        List<OptionsBean> options = getJdbcTemplate().query(getSQL(sql),params,
                new ListHandler());
        return options.size() > 0 ? (OptionsBean)options.get(0) : null;
    }    
    
    /**
     * 
     * inner class to implement org.springframework.jdbc.core.RowMapper
     *
     */
    private class ListHandler implements RowMapper
    {
        public Object mapRow(ResultSet rs, int row) throws SQLException
        {
            OptionsBean list = new OptionsBean(
                    rs.getString(1),// code
                    rs.getString(2));// value
            return list;
        }
    }
}
